import os
import mysql.connector as mysql

# 读取
def read_file(file_name):
    # 获取key文件的绝对路径
    file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), file_name)
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
        f.close()
    return content

def save(filename, contents):
  fh = open(filename, 'r+')
  fh.write(contents)
  fh.close()

def process(content):
    tempList = content.split("\\n");
    connectDatabase()
    for item in tempList:
        item = item.strip()
        if(item.startswith('tcp') or item.startswith('udp')):
            subList = item.split(" ")
            newList = [i for i in subList if i !='']
            if(newList[0].startswith("tcp")):
                port = newList[3].split(':')[-1]
                pid = newList[6].split('/')[0]
                pname = newList[6].split('/')[1]

            if(newList[0].startswith("udp")):
                port = newList[3].split(':')[-1]
                pid = newList[5].split('/')[0]
                pname = newList[5].split('/')[1]

            # 依据pname查找
            res = selectValue(pname)
            # 发现新服务
            if (len(res) == 0):
                insertValue(port, pid, pname, 0)
            else:  # 端口比较
                if (res[0][0] != port):  # 端口不一致，标记为动态进程
                    updateValue(pname, 1)
    return selectChanged(1)

def connectDatabase():
    global db
    try:
        db = mysql.connect(
            host="localhost",
            user="root",
            passwd="123123",
            database="db01"
        )
    except Exception as e:
        print("连接数据库失败"+e)

def insertValue(port,pid,pname,flag):
    query = "INSERT INTO serverinfo (pid, pname, port,changed) VALUES (%s, %s,%s,%s)"
    values = (pid, pname, port,flag)
    cursor = db.cursor()
    cursor.execute(query, values)
    db.commit()

def selectValue(pname):
    query = "SELECT pname,port FROM serverinfo WHERE pname = '%s'"%(pname);
    cursor = db.cursor()
    cursor.execute(query,pname)
    records = cursor.fetchall()
    return records

def selectChanged(flag):
    query = "SELECT * FROM serverinfo WHERE changed = '%s'"%(flag);
    cursor = db.cursor()
    cursor.execute(query)
    records = cursor.fetchall()
    return records

def updateValue(pname,flag):
    cursor = db.cursor()
    query = "UPDATE serverinfo SET changed = '%s' WHERE pname = '%s'"%(flag,pname);
    cursor.execute(query)
    db.commit()
